package com.dmp.onlinestore.controller;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dmp.onlinestore.system.Settings;
import com.dmp.onlinestore.view.base.ViewDefs;

public class ActionHandlerFactory {
	
	private static ActionHandlerFactory instance = null;
		
	// Hide the constructor.
	private ActionHandlerFactory () {
	}

	public static ActionHandlerFactory instance() {
		if (instance == null) {
			instance = new ActionHandlerFactory();
		}
		return instance;
	}
	
	// We could get a little fancier and create a hash of class types, index by request type and
	// instantiate the correct class using "forName". Maybe later...
	public ActionHandler getActionHandler(HttpServletRequest request, HttpServletResponse response) throws ControllerUnknownActionException {
		String action = (String) request.getParameter(ViewDefs.REQUEST_FIELD_ACTION);
		ActionHandler handler = null;
		if (Settings.CONSOLE_DEBUG_ON) {
			System.out.println("ActionHandlerFactory::getActionHandler; action is >>" + action + "<<");
		}
		if (action == null) {
			// Create a Null action handler, but only if there are no parameters.
			Enumeration e =  request.getParameterNames();
			if (! e.hasMoreElements()) {
				// No parameters; no particular action requested.
				if (Settings.CONSOLE_DEBUG_ON) {
					System.out.println("ActionHandlerFactory::getActionHandler; creating null handler");
				}
				handler = new ActionHandlerNoAction(request, response);
			}
		}
		else if (action.equals(ViewDefs.ACTION_GET_PRODUCTS)) {
			if (Settings.CONSOLE_DEBUG_ON) {
				System.out.println("ActionHandlerFactory::getActionHandler-getProducts");
			}
			handler = new ActionHandlerGetProducts(request, response);
		}
//		else if (action.equals(ViewUtilities.ACTION_CREATE_ACCOUNT)) {
//			System.out.println("T4.1");
//			handler = new ActionHandlerCreateAccount(request, response);
//		}
		else {
			if (Settings.CONSOLE_DEBUG_ON) {
				System.out.println("ActionHandlerFactory::getActionHandler-no supported action (else)");
			}
			throw new ControllerUnknownActionException();
		}
		if (handler == null) {
			if (Settings.CONSOLE_DEBUG_ON) {
				System.out.println("ActionHandlerFactory::getActionHandler-no supported action (null handler)");
			}
			throw new ControllerUnknownActionException();
		}
		else {
			return handler;
		}
	}
}
